﻿using BZ.Camera.MindVision;
using BZ.Logger;
using HalconDotNet;
using NDK.Module.BLL;
using NDK.Module.Model;
using NDK.Motion.BLL;
using NDK.Motion.MachineManager;
using NDK.Motion.Monitor;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static NDK.Module.Model.Common;

namespace NDK.Module.StationLogic
{
    [Monitor(Description = "量测工位")]
    public class MeasureStation : StationLogic
    {
        #region 通用
        //记录当前步骤，用于步骤变化的比较
        private StationStep _curStep = StationStep.开始准备;
        //对外提供工位的步骤变化事件
        public override event PropertyChangedEventHandler PropertyChanged;
        //对外提供唯一实例
        public static MeasureStation Instance = new MeasureStation();
        //私有化的构造函数
        private MeasureStation() : base()
        {
            this.Name = "量测工位";
        }
        //步骤字段、属性
        private StationStep _step = StationStep.开始准备;
        [Monitor(Description = "当前步骤")]
        public StationStep Step
        {
            get
            {
                return _step;
            }
            set
            {
                if (_curStep != value)
                {
                    _step = value;
                    _curStep = value;

                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(value.ToString()));
                }
            }
        }
        #endregion

        #region 变量

        HImage hImageLaser_平台1长边1 = new HImage();
        HImage hImageLaser_平台1长边2 = new HImage();
        HImage hImageLaser_平台1上激光 = new HImage();
        HImage hImageLaser_平台1上激光_fix1 = new HImage();
        HImage hImageLaser_平台1上激光_fix2 = new HImage();
        HImage hImageLaser_平台1短边1 = new HImage();
        HImage hImageLaser_平台1短边2 = new HImage();

        HImage hImageLaser_平台2长边1 = new HImage();
        HImage hImageLaser_平台2长边2 = new HImage();
        HImage hImageLaser_平台2上激光 = new HImage();
        HImage hImageLaser_平台2短边1 = new HImage();
        HImage hImageLaser_平台2短边2 = new HImage();

        HImage hImage_平台1_Capture1 = new HImage();
        HImage hImage_平台1_Capture2 = new HImage();
        HImage hImage_平台1_Capture3 = new HImage();
        HImage hImage_平台2_Capture1 = new HImage();
        HImage hImage_平台2_Capture2 = new HImage();
        HImage hImage_平台2_Capture3 = new HImage();
        private int CamImgCount = 0;

        Task task1, task2;
        List<bool> retList_Fix1 = new List<bool>() { true };
        List<bool> retList_Fix2 = new List<bool>() { true };

        public string Fix1LocalPath = "";
        public string Fix2LocalPath = "";
        public string Fix1SaveImgSN = "";
        public string Fix2SaveImgSN = "";

        object obj = new object();

        MeasureProduct MP1;
        MeasureProduct MP2;
        string[] SN;
        #endregion

        /// <summary>
        /// 工站初始化
        /// </summary>
        public override void Init()
        {
            base.Init();
            Step = StationStep.开始准备;
            logBaseInfo = "MeasureStation";

            CCD = MVCameraList.getObject("UpMeasureCCD");
            SNQueue = new ConcurrentQueue<string[]>();
            DataQueue1 = new ConcurrentQueue<MeasureProduct>();
            DataQueue2 = new ConcurrentQueue<MeasureProduct>();
        }

        private bool VacuumOn()
        {
            return VacuumMethod(true, (Machine.do_检测平台真空1吸, Machine.di_检测平台真空1反馈, !Common.屏蔽治具1), (Machine.do_检测平台真空2吸, Machine.di_检测平台真空2反馈, !Common.屏蔽治具2));
        }

        public void VacuumOff()
        {
            Machine.do_检测平台真空1吸.OFF();
            Machine.do_检测平台真空2吸.OFF();
            Machine.do_检测平台真空1破.ON();
            Machine.do_检测平台真空2破.ON();
            Thread.Sleep(150);
            Machine.do_检测平台真空1破.OFF();
            Machine.do_检测平台真空2破.OFF();
        }

        /// <summary>
        /// 工站动作流程
        /// </summary>
        /// <param name="mode"></param>
        public override void ActionProcess()
        {
            try
            {
                switch (Step)
                {
                    case StationStep.开始准备:
                        Step = StationStep.流程开始;
                        break;
                    case StationStep.流程开始:
                        if (isWriteLog)
                        {
                            logCtStr = string.Empty;
                            swStepTime.Restart();
                            swStationCT.Restart();
                            logCtStr += $"{logBaseInfo},MeasureStation 工站开始,{swStepTime.ElapsedMilliseconds},{Environment.NewLine}";
                            swStepTime.Restart();
                        }
                        Step = StationStep.工站原位;
                        break;

                    case StationStep.工站原位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_初始位) && MotionControl.AxesMove(Machine.pos_SideLaser_长边扫描位))
                        {
                            工位要料 = true;
                            Step = StationStep.等待上工站开完成;
                        }
                        break;

                    case StationStep.等待上工站开完成:
                        if (Transform.Instance.工位完成)
                        {
                            Common.sw10.Restart();
                            Transform.Instance.VacuumOff();
                            Step = StationStep.打开真空;
                        }
                        break;
                    case StationStep.打开真空:
                        if (VacuumOn())
                        {
                            工位要料 = false;
                            Step = StationStep.克隆数据;
                        }
                        break;

                    case StationStep.克隆数据:
                        SNQueue.TryDequeue(out SN);
                        Step = StationStep.等待上工位关完成信号;
                        break;

                    case StationStep.等待上工位关完成信号:
                        if (!Transform.Instance.工位完成)
                        {
                            Step = StationStep.运动到平台1长边扫描起始位;
                        }
                        break;

                    case StationStep.运动到平台1长边扫描起始位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_平台1长边扫描起始位))
                        {
                            Step = StationStep.打开激光群组1;
                        }
                        break;

                    case StationStep.打开激光群组1:
                        if (!屏蔽激光扫描)
                        {
                            SideLaser1.Start();
                            SideLaser2.Start();
                            UpLaser.Start();
                        }
                        Step = StationStep.运动到平台1长边扫描终点位;
                        break;

                    case StationStep.运动到平台1长边扫描终点位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_平台1长边扫描终点位))
                        {
                            MP1 = new MeasureProduct();
                            MP2 = new MeasureProduct();
                            Step = StationStep.关闭激光群组1;
                        }
                        break;

                    case StationStep.关闭激光群组1:
                        if (!屏蔽激光扫描)
                        {
                            if (UpLaser.Stop())
                                hImageLaser_平台1上激光 = UpLaser.HeightImage(10000);

                            if (hImageLaser_平台1上激光 == null)
                            {
                                if (AlarmPause("上激光采图超时", "上激光采图超时", "请检查上激光", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    UpLaser.Stop();
                                    Step = StationStep.运动到平台1长边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                hImageLaser_平台1上激光.GetImageSize(out int Width, out int Height);
                                if (!屏蔽治具1)
                                {
                                    hImageLaser_平台1上激光_fix1 = hImageLaser_平台1上激光.CropRectangle1(0, 0, Height / 2, Width);
                                    MP1.UpLaser = hImageLaser_平台1上激光_fix1;
                                }
                                if (!屏蔽治具2)
                                {
                                    hImageLaser_平台1上激光_fix2 = hImageLaser_平台1上激光.CropRectangle1(Height / 2, 0, Height, Width);
                                    MP2.UpLaser = hImageLaser_平台1上激光_fix2;
                                }
                            }


                            if (SideLaser1.Stop())
                                hImageLaser_平台1长边1 = SideLaser1.HeightImage(10000);

                            if (hImageLaser_平台1长边1 == null)
                            {
                                if (AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser1.Stop();
                                    Step = StationStep.运动到平台1长边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP1.SideLaser_长边1 = hImageLaser_平台1长边1;
                            }

                            if (SideLaser2.Stop())
                                hImageLaser_平台1长边2 = SideLaser2.HeightImage(10000);

                            if (hImageLaser_平台1长边2 == null)
                            {
                                if (AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser2.Stop();
                                    Step = StationStep.运动到平台1长边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP1.SideLaser_长边2 = hImageLaser_平台1长边2;
                            };
                        }
                        Step = StationStep.预运动到平台1短边扫描起始位;
                        break;
                    case StationStep.预运动到平台1短边扫描起始位:
                        if (!屏蔽治具1)
                        {
                            MotionControl.AxesMoveNoWait(Machine.pos_SideLaser_短边扫描位);
                            MotionControl.AxesMoveNoWait(Machine.pos_Measure_平台1短边扫描起始位);
                        }
                        Step = StationStep.运动到平台1短边扫描起始位;
                        break;

                    case StationStep.运动到平台1短边扫描起始位:
                        if (!屏蔽治具1)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_SideLaser_短边扫描位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台1短边扫描起始位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.打开激光群组2;
                        break;

                    case StationStep.打开激光群组2:
                        if (!屏蔽治具1)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.运动到平台1短边扫描终点位;
                                break;
                            }
                            SideLaser1.Start();
                            SideLaser2.Start();
                        }
                        Step = StationStep.运动到平台1短边扫描终点位;
                        break;

                    case StationStep.运动到平台1短边扫描终点位:
                        if (!屏蔽治具1)
                        {
                            if (!MotionControl.AxesMove(Machine.pos_Measure_平台1短边扫描终点位))
                                break;
                        }
                        Step = StationStep.关闭激光群组2;
                        break;

                    case StationStep.关闭激光群组2:
                        if (!屏蔽治具1)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.预运动到平台2长边扫描起始位;
                                break;
                            }

                            if (SideLaser1.Stop())
                                hImageLaser_平台1短边1 = SideLaser1.HeightImage(5000);

                            if (hImageLaser_平台1短边1 == null)
                            {
                                if (AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser1.Stop();
                                    Step = StationStep.运动到平台1短边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP1.SideLaser_短边1 = hImageLaser_平台1短边1;
                            }

                            if (SideLaser2.Stop())
                                hImageLaser_平台1短边2 = SideLaser2.HeightImage(5000);

                            if (hImageLaser_平台1短边2 == null)
                            {
                                if (AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser2.Stop();
                                    Step = StationStep.运动到平台1短边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP1.SideLaser_短边2 = hImageLaser_平台1短边2;
                            };
                        }
                        Step = StationStep.激光计算1;
                        break;

                    case StationStep.激光计算1:
                        if (!屏蔽治具1 && !屏蔽算法)
                        {
                            task1 = Task.Run(() =>
                             {
                                 List<DataItem> listDataItem1 = new List<DataItem>();
                                 List<DataItem> listDataItem2 = new List<DataItem>();
                                 string FileName1 = $"Side_Laser{AlgorithmNameDic[whichBlock]}".Trim();
                                 string FileName2 = $"TopLaser{AlgorithmNameDic[whichBlock]}".Trim();
                                 VisionResult_Laser(FileName1, "SideLaserData", ref listDataItem1, hImageLaser_平台1长边1, hImageLaser_平台1长边2, hImageLaser_平台1短边1, hImageLaser_平台1短边2, 1, SN[0]);
                                 VisionResult_Laser_Up(FileName2, "UpLaserData", ref listDataItem2, hImageLaser_平台1上激光_fix1, 1, SN[0]);
                                 MP1.MeasureData.AddRange(listDataItem1);
                                 MP1.MeasureData.AddRange(listDataItem2);
                             });
                        }
                        Step = StationStep.预运动到平台2长边扫描起始位;
                        break;
                    case StationStep.预运动到平台2长边扫描起始位:

                        Step = StationStep.运动到平台2长边扫描起始位;
                        break;

                    case StationStep.运动到平台2长边扫描起始位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_SideLaser_长边扫描位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台2长边扫描起始位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.打开激光群组3;
                        break;

                    case StationStep.打开激光群组3:
                        if (!屏蔽治具2)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.运动到平台2长边扫描终点位;
                                break;
                            }
                            SideLaser1.Start();
                            SideLaser2.Start();
                        }
                        Step = StationStep.运动到平台2长边扫描终点位;
                        break;

                    case StationStep.运动到平台2长边扫描终点位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台2长边扫描终点位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.关闭激光群组3;
                        break;

                    case StationStep.关闭激光群组3:
                        if (!屏蔽治具2)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.预运动到平台2短边扫描起始位;
                                break;
                            }


                            if (SideLaser1.Stop())
                                hImageLaser_平台2长边1 = SideLaser1.HeightImage(5000);

                            if (hImageLaser_平台2长边1 == null)
                            {
                                if (AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser1.Stop();
                                    Step = StationStep.预运动到平台2长边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP2.SideLaser_长边1 = hImageLaser_平台2长边1;
                            }

                            if (SideLaser2.Stop())
                                hImageLaser_平台2长边2 = SideLaser2.HeightImage(5000);

                            if (hImageLaser_平台2长边2 == null)
                            {
                                if (AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光2", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser2.Stop();
                                    Step = StationStep.预运动到平台2长边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP2.SideLaser_长边2 = hImageLaser_平台2长边2;
                            };

                        }
                        Step = StationStep.预运动到平台2短边扫描起始位;

                        break;

                    case StationStep.预运动到平台2短边扫描起始位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMoveNoWait(Machine.pos_SideLaser_短边扫描位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMoveNoWait(Machine.pos_Measure_平台2短边扫描起始位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.运动到平台2短边扫描起始位;
                        break;

                    case StationStep.运动到平台2短边扫描起始位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_SideLaser_短边扫描位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台2短边扫描起始位);
                            if (!axRes)
                                break;
                            Step = StationStep.打开激光群组4;
                        }
                        else
                        {
                            Step = StationStep.打开激光群组4;
                        }
                        break;

                    case StationStep.打开激光群组4:
                        if (!屏蔽治具2)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.运动到平台2短边扫描终点位;
                                break;
                            }
                            SideLaser1.Start();
                            SideLaser2.Start();
                        }
                        Step = StationStep.运动到平台2短边扫描终点位;
                        break;

                    case StationStep.运动到平台2短边扫描终点位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台2短边扫描终点位);
                            if (!axRes)
                                break;
                            Step = StationStep.关闭激光群组4;
                        }
                        else
                        {
                            Step = StationStep.侧激光轴回到初始位置;
                        }
                        break;

                    case StationStep.关闭激光群组4:
                        if (!屏蔽治具2)
                        {
                            if (屏蔽激光扫描)
                            {
                                Step = StationStep.侧激光轴回到初始位置;
                                break;
                            }

                            if (SideLaser1.Stop())
                                hImageLaser_平台2短边1 = SideLaser1.HeightImage(5000);

                            if (hImageLaser_平台2短边1 == null)
                            {
                                if (AlarmPause("侧激光1采图超时", "侧激光1采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser1.Stop();
                                    Step = StationStep.预运动到平台2短边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP2.SideLaser_短边1 = hImageLaser_平台2短边1;
                            }

                            if (SideLaser2.Stop())
                                hImageLaser_平台2短边2 = SideLaser2.HeightImage(5000);

                            if (hImageLaser_平台2短边2 == null)
                            {
                                if (AlarmPause("侧激光2采图超时", "侧激光2采图超时", "请检查侧激光1", "再次扫描", "忽略运行") == DialogResult.OK)
                                {
                                    SideLaser2.Stop();
                                    Step = StationStep.预运动到平台1短边扫描起始位;
                                    break;
                                }
                            }
                            else
                            {
                                MP2.SideLaser_短边2 = hImageLaser_平台2短边2;
                            };
                        }
                        Step = StationStep.激光计算2;
                        break;

                    case StationStep.激光计算2:
                        if (!屏蔽治具2 && !屏蔽算法)
                        {
                            task2 = Task.Run(() =>
                             {
                                 List<DataItem> listDataItem1 = new List<DataItem>();
                                 List<DataItem> listDataItem2 = new List<DataItem>();
                                 string FileName1 = $"Side_Laser{AlgorithmNameDic[whichBlock]}".Trim();
                                 string FileName2 = $"TopLaser{AlgorithmNameDic[whichBlock]}".Trim();
                                 VisionResult_Laser(FileName1, "SideLaserData", ref listDataItem1, hImageLaser_平台2长边1, hImageLaser_平台2长边2, hImageLaser_平台2短边1, hImageLaser_平台2短边2, 2, SN[1]);
                                 VisionResult_Laser_Up(FileName2, "UpLaserData", ref listDataItem2, hImageLaser_平台1上激光_fix2, 2, SN[1]);
                                 MP2.MeasureData.AddRange(listDataItem1);
                                 MP2.MeasureData.AddRange(listDataItem2);
                             });
                        }
                        Step = StationStep.侧激光轴回到初始位置;
                        break;

                    case StationStep.侧激光轴回到初始位置:
                        axRes = MotionControl.AxesMoveNoWait(Machine.pos_SideLaser_长边扫描位);
                        if (!axRes)
                            break;
                        axRes = MotionControl.AxesMoveNoWait(Machine.pos_Camera_拍照位);
                        if (!axRes)
                            break;
                        Step = StationStep.移动到平台1相机拍照位;
                        break;

                    case StationStep.移动到平台1相机拍照位:
                        if (!屏蔽治具1)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台1拍照位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMove(Machine.pos_SideLaser_长边扫描位);
                            if (!axRes)
                                break;
                            axRes = MotionControl.AxesMove(Machine.pos_Camera_拍照位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.平台1拍照1;
                        break;

                    case StationStep.平台1拍照1:
                        CamImgCount = 0;
                        if (!屏蔽治具1)
                        {
                            Machine.imageLights_量测平台1拍照1.Open();
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台1拍照2.Open();
                            }
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台1_Capture1 = CCD.Image();

                                if (hImage_平台1_Capture1 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP1.UpCamImage_1 = hImage_平台1_Capture1;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台1拍照2.Close();
                            }
                            Machine.imageLights_量测平台1拍照1.Close();

                        }
                        Step = StationStep.平台1拍照2;
                        break;

                    case StationStep.平台1拍照2:
                        CamImgCount = 0;
                        if (!屏蔽治具1)
                        {
                            Machine.imageLights_量测平台1拍照2.Open();//第二次拍照使用第一次拍照光源，亮度不同
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台1_Capture2 = CCD.Image();

                                if (hImage_平台1_Capture2 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP1.UpCamImage_2 = hImage_平台1_Capture2;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                            Machine.imageLights_量测平台1拍照2.Close();
                        }
                        Step = StationStep.平台1拍照3;
                        break;

                    case StationStep.平台1拍照3:
                        CamImgCount = 0;
                        if (!屏蔽治具1)
                        {
                            Machine.imageLights_量测平台1拍照3.Open();
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台1_Capture3 = CCD.Image();

                                if (hImage_平台1_Capture3 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP1.UpCamImage_3 = hImage_平台1_Capture3;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                            Machine.imageLights_量测平台1拍照3.Close();
                        }
                        Step = StationStep.视觉计算1;
                        break;

                    case StationStep.视觉计算1:
                        if (!屏蔽治具1 && !屏蔽算法)
                        {
                            Task.Run(() =>
                              {
                                  List<DataItem> listDataItem = new List<DataItem>();
                                  string FileName1 = $"CCD{AlgorithmNameDic[whichBlock]}".Trim();
                                  UpperCamVisionResult(FileName1, "CCDData",
                                           "Image0", hImage_平台1_Capture1,
                                           "Image1", hImage_平台1_Capture2,
                                           "Image2", hImage_平台1_Capture3, ref listDataItem,
                                           SN[0], 1);
                                  if (listDataItem != null)
                                  {
                                      task1.Wait();
                                      MP1.MeasureData.AddRange(listDataItem);
                                      var MP = CloneTempData(ref MP1);
                                      DataQueue1.Enqueue(MP);
                                  }
                              });
                        }
                        Step = StationStep.移动到平台2相机拍照位;
                        break;

                    case StationStep.移动到平台2相机拍照位:
                        if (!屏蔽治具2)
                        {
                            axRes = MotionControl.AxesMove(Machine.pos_Measure_平台2拍照位);
                            if (!axRes)
                                break;
                        }
                        Step = StationStep.平台2拍照1;
                        break;

                    case StationStep.平台2拍照1:
                        CamImgCount = 0;
                        if (!屏蔽治具2)
                        {
                            Machine.imageLights_量测平台2拍照1.Open();
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台2拍照2.Open();
                            }
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台2_Capture1 = CCD.Image();

                                if (hImage_平台2_Capture1 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP2.UpCamImage_1 = hImage_平台2_Capture1;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }

                            Machine.imageLights_量测平台2拍照1.Close();
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台2拍照2.Close();
                            }
                        }
                        Step = StationStep.平台2拍照2;
                        break;

                    case StationStep.平台2拍照2:
                        CamImgCount = 0;
                        if (!屏蔽治具2)
                        {
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台1拍照2.Open();//平台2第二次拍照与平台1第二次拍照一致
                            }
                            else
                            {
                                Machine.imageLights_量测平台2拍照2.Open();
                            }
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台2_Capture2 = CCD.Image();

                                if (hImage_平台2_Capture2 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP2.UpCamImage_2 = hImage_平台2_Capture2;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                            if (Common.Line != "MUR")
                            {
                                Machine.imageLights_量测平台1拍照2.Close();
                            }
                            else
                            {
                                Machine.imageLights_量测平台2拍照2.Close();
                            }
                        }
                        Step = StationStep.平台2拍照3;
                        break;

                    case StationStep.平台2拍照3:
                        CamImgCount = 0;
                        if (!屏蔽治具2)
                        {
                            Machine.imageLights_量测平台2拍照3.Open();
                            Thread.Sleep(光源打开延时);
                            if (!屏蔽相机采图)
                            {
                                CCD.Snap();
                                hImage_平台2_Capture3 = CCD.Image();

                                if (hImage_平台2_Capture3 == null)
                                {
                                    CamImgCount++;
                                    if (CamImgCount < 3)
                                    {
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                    else
                                    {
                                        if (AlarmPause("采图异常", "量测上CCD图像连续三次采集异常：", "请检查相机是否掉线及相机参数是否存在异常", " 再次拍照", "忽略继续") == DialogResult.OK)
                                        {
                                            CamImgCount = 0;
                                            PublicMethod.ReconnectCam(ref CCD, "UpMeasureCCD");
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    CamImgCount = 0;
                                    MP2.UpCamImage_3 = hImage_平台2_Capture3;
                                }
                            }
                            else
                            {
                                Thread.Sleep(300);
                            }
                            Machine.imageLights_量测平台2拍照3.Close();
                        }
                        Step = StationStep.视觉计算2;
                        break;

                    case StationStep.视觉计算2:
                        if (!屏蔽治具2 && !屏蔽算法)
                        {
                            Task.Run(() =>
                             {
                                 List<DataItem> listDataItemVision = new List<DataItem>();
                                 string FileName = $"CCD{AlgorithmNameDic[whichBlock]}".Trim();
                                 UpperCamVisionResult(FileName, "CCDData", "Image0", hImage_平台2_Capture1, "Image1", hImage_平台2_Capture2, "Image2", hImage_平台2_Capture3, ref listDataItemVision, SN[1], 2);
                                 if (listDataItemVision != null)
                                 {
                                     task2.Wait();
                                     MP2.MeasureData.AddRange(listDataItemVision);
                                     var MP = CloneTempData(ref MP2);
                                     DataQueue2.Enqueue(MP);
                                 }
                             });
                        }
                        Step = StationStep.保存平台1所有图像;
                        break;

                    case StationStep.保存平台1所有图像:
                        if (!屏蔽治具1)
                        {
                            

                            Step = StationStep.保存平台2所有图像;
                        }
                        else
                        {
                            Step = StationStep.保存平台2所有图像;
                        }
                        break;

                    case StationStep.保存平台2所有图像:
                        if (!屏蔽治具2)
                        {
                            

                            Step = StationStep.判断模式;
                        }
                        else
                        {
                            Step = StationStep.判断模式;
                        }
                        break;

                    case StationStep.判断模式:
                        if (!GRR循环模式 || Common.GRREnd)
                            Step = StationStep.等待下工位要料;
                        else
                            Step = StationStep.GRR移动到接料位;
                        break;

                    case StationStep.等待下工位要料:
                        if (UnloadFlip.Instance.工位要料)
                        {
                            Step = StationStep.移动到下料位;
                        }
                        break;

                    case StationStep.移动到下料位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_下料位))
                        {
                            工位完成 = true;
                            Step = StationStep.等待下工站关要料;
                        }
                        break;

                    case StationStep.等待下工站关要料:
                        if (!UnloadFlip.Instance.工位要料)
                        {
                            Step = StationStep.运动到避让位;
                        }
                        break;

                    case StationStep.运动到避让位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_初始位))
                        {
                            工位完成 = false;
                            Step = StationStep.流程结束;
                        }
                        break;

                    case StationStep.GRR移动到接料位:
                        if (MotionControl.AxesMove(Machine.pos_Measure_初始位))
                        {

                            Step = StationStep.GRR产品计算;
                        }
                        break;
                    case StationStep.GRR产品计算:
                        GRR工位完成 = true;
                        Step = StationStep.GRR等待上工位关要料;
                        break;

                    case StationStep.GRR等待上工位关要料:
                        if (!Transform.Instance.GRR工位要料)
                        {
                            GRR工位完成 = false;
                            Step = StationStep.流程结束;
                        }
                        break;

                    case StationStep.流程结束:
                        Common.sw10.Stop();
                        if (isWriteLog)
                        {
                            logCtStr += $"{logBaseInfo},Unload结束,{swStepTime.ElapsedMilliseconds},{Environment.NewLine}";
                            logCtStr += $"{logBaseInfo},Unload结束,{swStationCT.ElapsedMilliseconds},{Environment.NewLine}";
                            PublicMethod.WriteLogToTxt(logCtStr, $"000StepCT_{DateTime.Now.ToString("yyyyMMdd")}", "7.Unload");

                        }
                        Step = StationStep.开始准备;
                        break;
                }
            }
            catch (Exception ex)
            {
                UILog_Error($"[MeasureStation EmptyActionProcess Thread ERROR] {ex.Message}");
            }
        }

        public override void EmptyActionProcess()
        {
            ActionProcess();
        }

        public override void GRRActionProcess()
        {
            ActionProcess();
        }

        /// <summary>
        /// 工位步骤定义
        /// </summary>
        public enum StationStep
        {
            开始准备,
            流程开始,
            工站原位,
            等待上工站开完成,
            打开真空,
            克隆数据,
            等待上工位关完成信号,
            运动到平台1长边扫描起始位,
            打开激光群组1,
            运动到平台1长边扫描终点位,
            关闭激光群组1,
            预运动到平台1短边扫描起始位,
            运动到平台1短边扫描起始位,
            打开激光群组2,
            运动到平台1短边扫描终点位,
            关闭激光群组2,
            激光计算1,
            预运动到平台2长边扫描起始位,
            运动到平台2长边扫描起始位,
            打开激光群组3,
            运动到平台2长边扫描终点位,
            关闭激光群组3,
            预运动到平台2短边扫描起始位,
            运动到平台2短边扫描起始位,
            打开激光群组4,
            运动到平台2短边扫描终点位,
            关闭激光群组4,
            激光计算2,
            侧激光轴回到初始位置,
            移动到平台1相机拍照位,
            平台1拍照1,
            平台1拍照2,
            平台1拍照3,
            视觉计算1,
            移动到平台2相机拍照位,
            平台2拍照1,
            平台2拍照2,
            平台2拍照3,
            视觉计算2,
            保存平台1所有图像,
            保存平台2所有图像,
            判断模式,
            等待下工位要料,
            移动到下料位,
            等待下工站关要料,
            运动到避让位,

            GRR产品计算,
            GRR移动到接料位,
            GRR等待上工位关要料,
            流程结束,
        }


        public bool VisionResult_Laser(string FileName, string outDataName, ref List<DataItem> listDataItems, HImage inputImage1, HImage inputImage2, HImage inputImage3,
    HImage inputImage4, int inputCarrer = 0, string ID = "0")
        {
            try
            {
                //lock (obj)
                //{
                    AppendUiLog.Log($"侧Laser计算-------" + "PanNum:" + inputCarrer.ToString() + "ID:" + ID.ToString(), LogType.Alert);
                    string strResult = string.Empty;
                    VisionPlatform.VisionManager.Engine eng = null;
                    eng = new VisionPlatform.VisionManager.Engine(FileName);
                    eng.SetInputImage("Lasercb_1", inputImage1);
                    eng.SetInputImage("Lasercb_2", inputImage2);
                    eng.SetInputImage("Laserdb_1", inputImage3);
                    eng.SetInputImage("Laserdb_2", inputImage4);

                    eng.SetInputNumber("PanNum", inputCarrer);
                    eng.SetInputString("ID", ID);
                    eng.ActionFun();
                    strResult = eng.GetOutputString(outDataName);
                    if (strResult != "")
                    {
                        Dictionary<string, double> dic = new Dictionary<string, double>();
                        dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);

                        foreach (var item in dic)
                        {
                            string FAIName = item.Key;
                            string FAIValue = item.Value.ToString();

                            DataItem FAI = new DataItem();
                            FAI.Name = FAIName;
                            FAI.Value = double.Parse(FAIValue);
                            FAI.Position = 0;
                            listDataItems.Add(FAI);
                        }
                    }
                //}
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName}算法流程异常" + ex.ToString(), LogType.Error);
                return false;
            }

            return true;
        }

        public bool VisionResult_Laser_Up(string FileName, string outDataName, ref List<DataItem> listDataItems, HImage inputImage1, int inputCarrer = 0, string ID = "0")
        {
            try
            {
                //lock (obj)
                //{
                    AppendUiLog.Log($"上Laser计算-------" + "PanNum:" + inputCarrer.ToString() + "ID:" + ID.ToString(), LogType.Alert);
                    string strResult = string.Empty;
                    VisionPlatform.VisionManager.Engine eng = null;
                    eng = new VisionPlatform.VisionManager.Engine(FileName);
                    eng.SetInputImage("LaserUp", inputImage1);

                    eng.SetInputNumber("PanNum", inputCarrer);
                    eng.SetInputString("ID", ID);
                    eng.ActionFun();
                    strResult = eng.GetOutputString(outDataName);
                    if (strResult != "")
                    {
                        Dictionary<string, double> dic = new Dictionary<string, double>();
                        dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);

                        foreach (var item in dic)
                        {
                            string FAIName = item.Key;
                            string FAIValue = item.Value.ToString();

                            DataItem FAI = new DataItem();
                            FAI.Name = FAIName;
                            FAI.Value = double.Parse(FAIValue);
                            FAI.Position = 0;
                            listDataItems.Add(FAI);
                        }
                    }
                //}
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName}算法流程异常" + ex.ToString(), LogType.Error);
                return false;
            }

            return true;
        }


        public bool UpperCamVisionResult(string FileName, string outDataName, string inputImageName1, HImage InputImage1, string inputImageName2,
            HImage InputImage2, string inputImageName3, HImage InputImage3, ref List<DataItem> listDataItems, string inputID = "0", int inputFixtureID = 0)
        {
            try
            {
                //lock (obj)
                //{
                    AppendUiLog.Log($"CCD计算-------" + "PanNum:" + inputFixtureID.ToString() + "ID:" + inputID.ToString(), LogType.Alert);
                    string strResult = string.Empty;
                    VisionPlatform.VisionManager.Engine eng = null;
                    eng = new VisionPlatform.VisionManager.Engine(FileName);
                    eng.SetInputNumber("PanNum", inputFixtureID);
                    eng.SetInputString("ID", inputID);
                    eng.SetInputImage(inputImageName1, InputImage1);
                    eng.SetInputImage(inputImageName2, InputImage2);
                    eng.SetInputImage(inputImageName3, InputImage3);
                    eng.ActionFun();
                    strResult = eng.GetOutputString(outDataName);

                    if (strResult != "")
                    {
                        Dictionary<string, double> dic = new Dictionary<string, double>();
                        dic = JsonConvert.DeserializeObject<Dictionary<string, double>>(strResult);
                        foreach (var item in dic)
                        {
                            string FAIName = item.Key;
                            string FAIValue = item.Value.ToString();
                            DataItem FAI = new DataItem();
                            FAI.Name = FAIName;
                            FAI.Value = double.Parse(FAIValue);
                            FAI.Position = 0;
                            listDataItems.Add(FAI);
                        }
                    }
                //}
            }
            catch (Exception ex)
            {
                AppendUiLog.Log($"{FileName}算法流程异常" + ex.ToString(), LogType.Error);
                return false;
            }

            return true;
        }

    }
}
